<template>
  <div class="ky-container schedule-container" @click="scheduleDlgClose">
    <el-card shadow="hover" class="ky-card-xs ky-card-hdbg">
      <el-row>
        <el-col :span="18">
          <el-form
            :inline="true"
            :model="formdata"
            @submit.native.prevent
            class="ky-form-inline ky-form-inline-sm"
          >
            <el-form-item label="医院机房">
              <roomCascader
                :room.sync="formdata.room"
                :refresh-local="true"
                @roomChange="roomChange"
              ></roomCascader>
            </el-form-item>
            <el-form-item v-if="formdata.room.length > 0">
              <el-tooltip
                class="item"
                effect="dark"
                content="刷新"
                placement="top-start"
              >
                <i
                  @click="refreshTemplate"
                  class="el-icon-refresh"
                  style="margin-top: 12px; cursor: pointer"
                ></i>
              </el-tooltip>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <div style="text-align: right; line-height: 46px">
            <el-button
              v-permission="'YJYY10001001001'"
              size="small"
              @click="goRouterScheduleManage"
            >机房号源管理</el-button
            >
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card
      shadow="hover"
      class="ky-card-xs ky-card-hdbg ky-mt10"
      v-show="formdata.room.length > 0"
    >
      <div class="appo-header">
        <el-form
          :inline="true"
          :model="appoFormData"
          class="ky-form-inline ky-form-inline-sm"
        >
          <el-form-item>
            <week @weekChange="weekChange" :cur-date.sync="curDate"></week>
          </el-form-item>
          <el-form-item class="item-line-36">
            <el-checkbox
              v-model="appoFormData.type"
              @change="appoShowType"
            >仅显示正常预约号源</el-checkbox
            >
          </el-form-item>
          <!-- <el-form-item class="item-line-36">
            <el-radio-group v-model="appoFormData.type" style="margin-top: 0px;" @change="appoShowType">
              <el-radio :label="1">仅显示正常预约排班段</el-radio>
              <el-radio :label="0">显示所有排班段</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-form>
        <div v-permission="'YJYY10001001001'">
          <el-switch
            v-model="appoFormData.edit"
            active-text="启用编辑"
            inactive-text="禁用编辑"
            @change="fsStatusChange"
          >
          </el-switch>
        </div>
      </div>
      <fullscheduleTips></fullscheduleTips>
      <div class="appo-main" v-loading="loading">
        <fullschedule
          ref="fullschedule"
          :is-edit="appoFormData.edit"
          :is-add="false"
          :status-filter="statusFilter"
          :sidebardata="sidebardata"
          :row-height="84"
          :del-send="true"
          :hospital-code="checkRoomObj.HospitalCode"
          @addNewSchedule="addNewSchedule"
          @handleAppoInfo="handleAppoInfo"
          @handleAppoDel="handleAppoDel"
          @openSourceInfoDialog="openSourceInfoDialog"
        ></fullschedule>
      </div>
    </el-card>
    <roomNone v-show="formdata.room.length === 0"></roomNone>
    <scheduleTemplateForm
      ref="scheduleTemplateForm"
      :temp-title.sync="tempTitle"
      @addScheduleTempSave="addScheduleTempSave"
      @editScheduleTempSave="editScheduleTempSave"
      @openSourceInfoDialog="openSourceInfoDialog"
    ></scheduleTemplateForm>
    <!-- 查看预约信息详情 -->
    <appoReleaseInfo
      :hospital-code="checkRoomObj.HospitalCode"
      :dep="checkRoomObj.Dep"
      ref="appoReleaseInfo"
      @openSourceInfoDialog="openSourceInfoDialog"
    ></appoReleaseInfo>
    <!-- 编辑预约信息 -->
    <appoReleaseInfoEdit
      ref="appoReleaseInfoEdit"
      @updateAppo="editScheduleTempSave"
    ></appoReleaseInfoEdit>
    <!-- 锁定号源信息 -->
    <sourceInfoDialog
      :visible.sync="sourceInfoVisible"
      :s-data="sData"
    ></sourceInfoDialog>
  </div>
</template>

<script>
import { setSidebarDataTemp, setSidebarData } from '@/utils/utils' // this.$utils
import { getHospitalSetting, deleteAppLists } from '@/api/api'
import { getAppointmentList } from '@/api/room'
import fullschedule from '../components/fullschedule'
import fullscheduleTips from '../components/fullscheduleTips'
import week from '../components/week'
import roomCascader from '../components/roomCascader'
import scheduleTemplateForm from '../components/scheduleTemplateForm'
import appoReleaseInfo from '../components/appoReleaseInfo'
import appoReleaseInfoEdit from '../components/appoReleaseInfoEdit'
import roomNone from '@/components/roomNone'
import { dateFormatter } from '@/utils/validate'
import { getWeekStartEndDate, seasonCalCurrDate } from '@/utils/schedule'
import sourceInfoDialog from '../components/sourceInfoDialog2.vue'

export default {
  provide() {
    return {
      tempListUpdate: this.tempListUpdate
    }
  },
  components: {
    week,
    fullschedule,
    fullscheduleTips,
    roomCascader,
    scheduleTemplateForm,
    appoReleaseInfo,
    appoReleaseInfoEdit,
    roomNone,
    sourceInfoDialog
  },
  data() {
    return {
      sourceInfoVisible: false,
      sData: {},
      loading: false,
      formdata: {
        room: []
      },
      appointmentData: [],
      curDate: dateFormatter(new Date()),
      tempTitle: '编辑机房号源', // 排班新增弹框标题
      checkRomeArr: [], // 查询数据机房联级数组
      // 机房，查询条件数据
      checkRoomObj: {
        HospitalCode: '',
        StartDate: '',
        EndDate: '',
        DepArea: '',
        Dep: '',
        ModalityType: '',
        CheckRoom: '',
        AppointmentStatus: '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班；单选
        IsHasFilters: true
      },

      // 排班条件
      appoFormData: {
        month: '',
        week: '',
        day: '',
        status: 'week', // week: 周，month: 月
        edit: false, // 是否启用编辑
        type: true // false 仅显示正常预约段
      },

      // 排班
      sidebardata: [
        // {
        //   title: '上午班',
        //   start: '8:00',
        //   end: '12:00',
        //   barHeight: 0,
        //   timegather: []
        // },
        // {
        //   title: '下午班',
        //   start: '13:00',
        //   end: '17:30',
        //   barHeight: 0,
        //   timegather: []
        // }
        // {
        //   title: '晚上班',
        //   start: '18:00',
        //   end: '21:30',
        //   barHeight: 0,
        //   timegather: []
        // }
      ],
      statusFilter: '正常预约'
    }
  },
  created() {
    // this.formdata.room = this.$store.state.user.checkRoom
  },
  mounted() {
    // this.init(this.formdata.room)
  },
  methods: {
    openSourceInfoDialog(val) {
      // 打开号源锁定时段信息
      this.sourceInfoVisible = true
      this.sData = val
    },
    async init(data) {
      console.log(111111, data)
      if (JSON.stringify(this.checkRomeArr) === JSON.stringify(data)) { return false }
      if (data && data.length > 0) {
        this.scheduleDlgClose()
        this.$refs.scheduleTemplateForm.close()
        this.checkRomeArr = [...data]
        this.checkRoomObj.HospitalCode = data[0]
        this.checkRoomObj.DepArea = data[1]
        this.checkRoomObj.Dep = data[2]
        this.checkRoomObj.ModalityType = data[3]
        this.checkRoomObj.CheckRoom = data[4]
        this.loading = true
        await this.getWeekDateTimeFull()
        const appodata = await getAppointmentList(this.checkRoomObj)
        await this.getAppoTimeTemp()
        await this.$refs.fullschedule.init({
          date: this.curDate,
          sidebardata: this.sidebardata
        })
        this.loading = false
        this.getAppoList(appodata)
      }
    },
    // 查询，获取排班数据
    async getAppoList(appodata) {
      console.log(22222, appodata)
      this.loading = true
      const _appodata =
        appodata || (await getAppointmentList(this.checkRoomObj))
      this.loading = false
      this.$refs.fullschedule.appoPull(_appodata)
    },
    // 获取排班一周的完整时间数组
    getWeekDateTimeFull() {
      return new Promise(async (resolve) => {
        this.weekDateFull = await getWeekStartEndDate(this.curDate)
        if (this.weekDateFull.length > 0) {
          this.checkRoomObj.StartDate = this.weekDateFull[0]
          this.checkRoomObj.EndDate =
            this.weekDateFull[this.weekDateFull.length - 1]
        }
        resolve()
      })
    },
    // 获取时段数据,计算时段
    getAppoTimeTemp() {
      return new Promise(async (resolve) => {
        const depArr = (this.checkRoomObj.Dep && this.checkRoomObj.Dep.indexOf('-') > -1 && this.checkRoomObj.Dep.split('-')) || ''
        let dep = (depArr && depArr.length && depArr[depArr.length - 1]) || ''
        if (this.checkRoomObj.Dep && this.checkRoomObj.Dep.indexOf('-') == -1) {
          dep = this.checkRoomObj.Dep
        }
        const param = {
          HospitalCode: this.checkRoomObj.HospitalCode,
          depArea: this.checkRoomObj.DepArea,
          dep
        }
        await getHospitalSetting(param).then(async (res) => {
          if (res && res.code === 10000) {
            const season = await seasonCalCurrDate(
              res.content.seasonSettings,
              this.weekDateFull[0],
              true
            )
            // 获取时令数组
            this.sidebardata = season.sidebardata
            // console.log('打印时令数组this.sidebardata', this.sidebardata)
            setSidebarData(JSON.stringify(season.sidebardata))
            // 获取模板的时间轴
            const seasonTemp = seasonCalCurrDate(res.content.seasonSettings, this.weekDateFull[0], true, false, true)
            setSidebarDataTemp(JSON.stringify(seasonTemp.sidebardata))
          }
        })
        resolve()
      })
    },
    // 当前排班类型切换
    scheduleChange() {
      this.appoFormData.status =
        this.appoFormData.status === 'week' ? 'month' : 'week'
    },
    // 机房改变
    async roomChange(roomData) {
      console.log('roomChange:==============', roomData)
      this.scheduleDlgClose()
      if (roomData && roomData.length > 0) {
        this.checkRomeArr = [...roomData]
        this.checkRoomObj.HospitalCode = roomData[0]
        this.checkRoomObj.DepArea = roomData[1]
        this.checkRoomObj.Dep = roomData[2]
        this.checkRoomObj.ModalityType = roomData[3]
        this.checkRoomObj.CheckRoom = roomData[4]
        this.loading = true
        await this.getWeekDateTimeFull()
        await this.getAppoTimeTemp()
        const appodata = await getAppointmentList(this.checkRoomObj)
        await this.$refs.fullschedule.init({
          date: this.curDate,
          sidebardata: this.sidebardata
        })
        this.loading = false
        this.getAppoList(appodata)
      }
      this.$store.dispatch('user/getDefaultCheckRoom', roomData)
    },
    // 周-变化
    async weekChange(data) {
      // 计算查询的周起始,结束时间
      console.log(1)
      this.loading = true
      await this.getWeekDateTimeFull()
      console.log(2)
      // 计算时令时段
      await this.getAppoTimeTemp()
      console.log(3)
      const appodata = await getAppointmentList(this.checkRoomObj)
      // 初始预约排班
      await this.$refs.fullschedule.init({
        date: this.curDate,
        sidebardata: this.sidebardata
      })
      this.loading = false
      // 加载数据
      this.getAppoList(appodata)
    },
    // 刷新
    async refreshTemplate() {
      this.loading = true
      console.log(4)
      const appodata = await getAppointmentList(this.checkRoomObj)
      // 初始预约排班
      await this.$refs.fullschedule.init({
        date: this.curDate,
        sidebardata: this.sidebardata
      })
      this.loading = false
      // 加载数据
      this.getAppoList(appodata)
    },

    // 新增排班模板
    addNewSchedule(data) {
      // console.log('addNewSchedule:====', data)
      const bTime = data.timeSel.split('-')[0]
      const eTime = data.timeSel.split('-')[1]
      const minMaxNum = this.$refs.fullschedule.getInitialMinMaxNum(
        bTime,
        eTime
      )
      const stfData = {
        time: data.time,
        appoInfo: null,
        room: this.checkRomeArr,
        timeSel: data.timeSel,
        minMaxNum
      }
      this.$refs.appoReleaseInfoEdit.close()
      this.$refs.appoReleaseInfo.close()
      this.$refs.scheduleTemplateForm.init(stfData)
    },
    addScheduleTempSave(data) {
      console.log('addScheduleTempSave:====', data)
      this.$refs.fullschedule.addNew(data)
    },
    editScheduleTempSave(data) {
      console.log('editScheduleTempSave:====', data)
      this.$refs.fullschedule.editUpdate(data)
    },
    // 查看、编辑预约排班信息
    handleAppoInfo(data) {
      console.log({ ...data })
      // data.disableDate 判断今天之前的是否可以编辑
      if (this.appoFormData.edit && !data.disableDate) {
        const stfData = {
          time: data.time,
          appoInfo: data.appoInfo,
          room: this.checkRomeArr
        }
        this.$refs.scheduleTemplateForm.close()
        this.$refs.appoReleaseInfo.close()
        this.$refs.appoReleaseInfoEdit.init(stfData)
      } else {
        this.$refs.scheduleTemplateForm.close()
        this.$refs.appoReleaseInfoEdit.close()
        this.$refs.appoReleaseInfo.init(data.appoInfo)
      }
    },
    // 删除排班时段数据
    handleAppoDel(appoInfo) {
      console.log(appoInfo)
      const params = {
        HospitalCode: this.checkRoomObj.HospitalCode,
        Id: appoInfo.id
      }
      this.$confirm('删除预约时段数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          deleteAppLists(params).then((res) => {
            this.loading = false
            if (res && res.code === 10000) {
              // bus.$emit('delAppoSuccess')
              this.$refs.fullschedule.appoDelSuccessCb()
            }
          })
        })
        .catch(() => {})
    },
    // 修改返回
    updateAppoCb() {},

    // 显示条件改变
    appoShowType(val) {
      this.statusFilter = !val
        ? '暂停预约、节假日、正常预约、设备故障、计划排班'
        : '正常预约'
      if (val) {
        this.appoFormData.edit = false
      }
    },
    // 路由跳转，机房号源管理
    goRouterScheduleManage() {
      // this.$store.dispatch('setting/tigger_isShowEditScedule', true)
      this.$router.push('/schedule/manage')
    },
    fsStatusChange(val) {
      if (val) {
        this.appoFormData.type = false
        this.appoShowType(false)
      }
    },
    tempListUpdate() {
      // console.log(22)
    },
    // 关闭弹框
    scheduleDlgClose() {
      this.$refs.appoReleaseInfo && this.$refs.appoReleaseInfo.close()
      this.$refs.appoReleaseInfoEdit && this.$refs.appoReleaseInfoEdit.close()
      this.$refs.scheduleTemplateForm &&
        this.$refs.scheduleTemplateForm.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.schedule-container {
  height: calc(100vh - 50px);
  overflow-y: auto;
}
.appo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-line-36 /deep/ .el-form-item__content {
  line-height: 36px;
}

.releaseauto {
  margin: 0 20px;
  cursor: pointer;
  font-size: 14px;
  .dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
    background-color: rgb(67, 207, 32);
  }
}
</style>
